<script lang="ts" setup>
import { ref, defineEmits } from 'vue'
import { message } from 'ant-design-vue'
import { useVbenModal } from '@vben/common-ui'
import { doColorInfo, doColorAdd, doColorEdit, getColorGroupList } from '#/api/color'
import { useDebounceFn } from '@vueuse/core'
import { useVbenForm } from '#/adapter/form'

const colorId = ref<Number>()
const formData = ref<any>({})
const keyword = ref<Record<string, string>>({
  group_id: '',
})
const title = ref('新增颜色')
const emit = defineEmits(['fetch-data'])
const data = ref<any>()

/**
 * 初始化清空
 */
const initClear = async () => {
  colorId.value = 0
  formData.value = {}
  Object.keys(keyword.value).forEach((key: string) => {
    ;(keyword.value as Record<string, string>)[key] = ''
  })
}

/**
 * 初始化
 */
const init = async () => {
  // 初始化逻辑
}

/**
 * 获取数据
 */
const fetchData = async () => {
  if (colorId.value) {
    let { row } = await doColorInfo({ id: colorId.value })
    Object.keys(keyword.value).forEach((key: string) => {
      if (row[key]) {
        ;(keyword.value as Record<string, string>)[key] = 'initValue:' + row[key]
      }
    })
    formApi.setValues(row)
    formData.value = row
  }
}

/**
 * 获取颜色分组选项（远程搜索）
 */
const fetchColorGroupOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = ''
  let initValue = ''
  let initKey = 'id'

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
  } else {
    quick_search = keyword
  }

  const { list } = await getColorGroupList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
  })

  return list.map((item: any) => ({
    label: item.title,
    value: item.group_id,
  }))
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1',
  layout: 'horizontal',
  schema: [
    {
      component: 'ApiSelect',
      fieldName: 'group_id',
      label: '颜色分组',
      rules: 'selectRequired',
      componentProps: () => ({
        api: fetchColorGroupOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.group_id = value
        }, 300),
        params: { keyword: keyword.value.group_id || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.group_id = ''
        },
      }),
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入颜色名称',
      },
      fieldName: 'name',
      label: '颜色名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入颜色编号(商企编)',
      },
      fieldName: 'code',
      label: '编号(商企编)',
      rules: 'required',
    },
  ],
  handleSubmit: async (value) => {
    const { valid } = await formApi.validate()
    if (valid) {
      try {
        modalApi.lock()
        if (colorId.value) {
          await doColorEdit({ ...value, id: colorId.value })
          message.success('编辑成功')
        } else {
          await doColorAdd(value)
          message.success('添加成功')
        }
        emit('fetch-data')
        modalApi.close()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        modalApi.unlock()
      }
    }
  },
  handleReset: () => {
    modalApi.close()
  },
  showDefaultActions: false,
})

const [Modal, modalApi] = useVbenModal({
  class: 'w-1/2',
  destroyOnClose: true,
  onClosed: () => {
    initClear()
    formApi.resetForm()
  },
  onOpenChange: (isOpen: boolean) => {
    if (isOpen) {
      data.value = modalApi.getData<Record<string, any>>()
      title.value = data.value?.info?.id ? '编辑颜色' : '新增颜色'

      if (data.value?.info?.id) {
        colorId.value = data.value.info.id
      }

      init()
      fetchData()
    }
  },
  onCancel: () => {
    modalApi.close()
  },
  onConfirm: () => {
    formApi.submitForm()
  },
})
</script>

<template>
  <Modal :title="title">
    <Form />
  </Modal>
</template>
